package com.barunsw.bwf.common.downloadview;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.web.servlet.view.AbstractView;

public class FileDownloadView extends AbstractView {
	
	public FileDownloadView() {
        this.setContentType("application/download; utf-8");
    }

	@Override
	protected void renderMergedOutputModel(Map<String, Object> dataMap,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		File file = (File) dataMap.get("attachFile");
		
		response.setContentType(this.getContentType());
		response.setContentLength((int) file.length());
		
		String userAgent 	= request.getHeader("User-Agent");
		String fileName 	= null;

		// IE Browser
		if ( userAgent.indexOf("MSIE") > -1 ) {
			fileName = URLEncoder.encode(file.getName(), "utf-8");
		} 
		else {
			fileName = new String(file.getName().getBytes("utf-8"), "iso-8859-1");
		}
		
		response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");
		response.setHeader("Content-Transfer-Encoding", "binary");
		
		OutputStream out 	= response.getOutputStream();
		InputStream	in		= null;
         
        try {
        	in = new FileInputStream(file);
            IOUtils.copy(in, out);
        } 
        catch ( Exception ex ) {
            ex.printStackTrace();
        } 
        finally {
        	if ( in != null ) {
        		try {
        			in.close();
        		} 
        		catch ( Exception ex ) {
        			ex.printStackTrace();
        		}
        	}
        	
        	if ( out != null ) {
        		try {
        			out.flush();
        			out.close();
        		}
        		catch ( Exception ex ) {
        			ex.printStackTrace();
        		}
        	}
        }
	}
}
